package com.imooc.course.service;

import com.imooc.course.dto.CourseDTO;
import com.imooc.course.mapper.CourseMapper;
import com.imooc.course.thrift.ServiceProvider;
import com.imooc.thrift.user.UserInfo;
import com.imooc.thrift.user.dto.TeacherDTO;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.thrift.TException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author LiJian
 * @date 2022/10/25
 */
@DubboService(registry="zk-registry")
public class CourseServiceImpl implements ICourseService {
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private ServiceProvider serviceProvider;

    @Override
    public List<CourseDTO> courseList() {
        List<CourseDTO> courseDTOS = courseMapper.listCourse();
        if (CollectionUtils.isNotEmpty(courseDTOS)) {
            for (CourseDTO courseDTO : courseDTOS) {
                Integer teacherUserId = courseMapper.getCourseTeacher(courseDTO.getId());
                // 得到用户的信息
                try {
                    UserInfo userInfo = serviceProvider.getUserService().getTeacherById(teacherUserId);
                    courseDTO.setTeacherDTO(trans2Teacher(userInfo));
                } catch (TException e) {
                    e.printStackTrace();
                }
            }
        }
        return courseDTOS;
    }

    private TeacherDTO trans2Teacher(UserInfo userInfo) {
        TeacherDTO teacherDTO = new TeacherDTO();
        BeanUtils.copyProperties(userInfo, teacherDTO);
        return teacherDTO;
    }
}
